<template>
  <div>
    <div>
      <div v-if="!noTip">
        <div style="text-align: right">
          <el-tooltip class="item" effect="dark" content="您没有安装DHPlayer插件，无法播放视频，请点击此处下载后解压安装再重新打开" placement="bottom-end">
            <a href="../DHPlayer.zip" target="_blank">
              视频播放插件下载
              <img :src="imgIcon" style="width: 25px;height: 25px">
            </a>
          </el-tooltip>
        </div>
      </div>
      <!--      <video ref="videoPlay" controls preload="auto" autoplay="true" style="width: 100%;height: 500px" />-->
      <div v-if="!noTip" class="videlSytle" style="width: 100%;height: 500px;" />
      <div v-else :id="videoId" ref="video1" style="width: 100%;height: 500px;" />
    </div>
  </div>
</template>

<script>
// import Hls from 'hls.min'
import '../../components/DHPlayer/videoPlayer'
import fn from '../../components/DHPlayer/factory'
export default {
  name: 'PlayVideo',
  props: {
    playVisible: {
      type: Boolean,
      default: false
    },
    multiPlayerAddess: {
      type: Array,
      default: () => { return [] }
    },
    videoNum: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      width: this.initWidth(),
      imgIcon: require('@/assets/videoDown.png'),
      pathList: ['rtmp://ns8.indexforce.com/home/mystream',
        {
          path: 'rtmp://ns8.indexforce.com/home/mystream',
          redirect: false
        }], // 实时预览测试
      videoId: '1',
      pathList2: [],
      videoPlayList: [],
      shieldClass: [], // 遮挡的元素class，尽量保证class元素的唯一
      realTimeList: [], // 实时预览列表
      outContent: {
        top: 0,
        left: 0
      },
      type: 1, // 视频类型，1-实时视频，2-录像回放
      showBar: true, // 是否显示下方控制栏。 true: 显示， false：隐藏
      connectTime: 60, // 尝试连接事件，默认60s，一定时间连接断开，并弹出下载插件提示。
      path: '',
      path2: '',
      noTip: false,
      DHPVisible: false,
      windowType: 0,
      currentNum: 0,
      upgradeDHP: false,
      videoPlayer: null,
      DHPVersion: '',
      startDownload: false,
      videoType: 'video1',
      api: fn(this),
      doc: '',
      screenWidth: 0
    }
  },
  computed: {
    isVisible: {
      get() {
        return this.playVisible
      },
      set() {
        this.destroy()
        this.close()
      }
    }
  },
  watch: {
    multiPlayerAddess(newValue, preValue) {
      if (newValue.length > 0) {
        console.log('多个播放视频地址：', newValue)
        setTimeout(() => {
          this.setMultiForm(newValue)
        }, 1000)
      }
    }
  },
  mounted() {
    this.initVideo(1)
  },
  methods: {
    // 销毁视频
    destroy() {
      this.videoPlayer.destroy()
    },
    setSingleForm(val) {
      console.log('单个播放视频地址：', val)
      this.path = val
      this.setRealTime({
        path: val,
        redirect: false,
        snum: 0
      })
    },
    setMultiForm(val) {
      if (val.length > 0) {
        val.forEach((v, index) => {
          this.setRealTime({
            path: v,
            redirect: false,
            snum: index
          })
        })
      }
    },
    // 初始化视频插件
    initVideo(videoNum) {
      if (this.videoPlayer) {
        this.destroy()
      }
      // eslint-disable-next-line no-undef
      this.videoPlayer = new VideoPlayer({
        videoId: this.videoId,
        windowType: this.windowType,
        connectTime: this.connectTime,
        shieldClass: this.shieldClass,
        showBar: this.showBar,
        num: videoNum,
        outContent: this.outContent,
        connectSuccess: () => {
          this.noTip = true
          this.DHPVersion = window.dhPlayerControl.DHPlayerVersion
          this.getVideoInfo(true)
        },
        // 录像回放时间栏拖拽回调
        switchStartTime: ({
          startTime,
          snum
        }) => {
          const record = this.playbackList[snum]
          if (record) {
            if (record.request) {
              const videoParams = this.videoPlayList[snum]
              const endTime = videoParams.endTime
              if (startTime > endTime) {
                !this.noTip && this.$message.warning('开始时间不得大于结束时间')
                this.$emit('getError', '开始时间不得大于结束时间')
                return false
              }
              this.dealRecord({
                ...videoParams,
                startTime
              }, snum)
            } else {
              const endTime = this.getUrlParam(record.path, 'endtime') - 0
              if (startTime > endTime) {
                !this.noTip && this.$message.warning('开始时间不得大于结束时间')
                this.$emit('getError', '开始时间不得大于结束时间')
                return false
              }
              this.setPlayback({
                ...record,
                playStartTime: startTime
              }, snum)
            }
          }
          this.$emit('switchStartTime', {
            startTime,
            snum
          })
        },
        videoDownloadSuccess: (path) => {
          !this.noTip && this.$message.success(`本地录像已存到 ${path}`)
          this.$emit('videoDownloadSuccess', path)
        },
        createSuccess: (e) => {
          if (!this.showBar) {
            this.setShowBar(false)
          }
          if (this.pathList.length) {
            this.loadVideo()
          } else {
            this.getRTSPURL()
          }
        }
      })
    },
    // 显隐控制栏
    setShowBar(show) {
      this.videoPlayer.showControlBar(show)
    },
    // 根据路径获取视频
    loadVideo() {
      if (this.type === 1) {
        this.pathList.forEach((val, index) => {
          let item = {
            snum: index
          }
          if (typeof val === 'string') {
            item.path = val
          } else if (typeof val === 'object') {
            item = { ...item, ...val }
          } else {
            return val
          }
          this.setRealTime(item)
        })
      } else {
        const list = []
        this.pathList.forEach((val, index) => {
          list.push({
            ...val,
            request: false
          })
          this.setPlayback(val, index)
        })
        this.playbackList = list
      }
    },
    // 获取录像回放/实时预览路径
    getRTSPURL() {
      let streamType = 1
      if (this.type === 1) {
        streamType = this.realTimeList.length >= 4 ? 2 : 1
        this.realTimeList.forEach((val, index) => {
          this.api.fetchRealRTSP({
            data: {
              streamType: val.streamType || streamType,
              channelId: val.channelId,
              dataType: val.dataType || 1
            }
          }).then(data => {
            if (data.url) {
              const url = this.dealUrl(data)
              this.setRealTime({
                path: url,
                redirect: typeof val.redirect === 'boolean' ? val.redirect : url.indexOf(':9090') !== -1,
                snum: index
              })
            }
          })
        })
      } else {
        streamType = this.videoPlayList.length >= 4 ? 2 : 1
        this.videoPlayList.forEach((val, index) => {
          this.dealRecord(val, index)
        })
      }
    },
    // 实时预览
    setRealTime(options) {
      this.videoPlayer.realmonitor({
        ...options
      })
    },
    /**
             * @method 获取录像插件版本
             * @param {Boolean} success 判断ws是否连接成功，true: 成功，比较版本号；false: 失败,下载插件
             **/
    getVideoInfo(success) {
      this.api.videoInfo().then(res => {
        if (res.version) {
          res.version = '000000'
        }
        if (success && res.version > this.DHPVersion) {
          this.upgradeDHP = true
          !window.DHPVisible && (window.DHPVisible = this.DHPVisible = true)
        }
        if (!success) {
          !window.DHPVisible && (window.DHPVisible = this.DHPVisible = true)
        }
      }).catch((e) => {
        if (!success) {
          !window.DHPVisible && (window.DHPVisible = this.DHPVisible = true)
        }
      })
    },
    // 隐藏插件更新/下载提示
    hiddenDhp() {
      window.DHPVisible = this.DHPVisible = false
    },
    // 修改url
    changeUrl() {
      if (this.videoType === 'video1') {
        this.pathList[0] = this.path
        this.setRealTime({
          path: this.path,
          redirect: false,
          snum: 0
        })
      } else {
        this.pathList2[0] = {
          url: this.path2
        }
        this.$refs[this.videoType].setPlayback({
          path: this.path2
        }, 0)
      }
    },
    // 获取当前选中的窗口
    getCurrentWindow(num) {
      this.currentNum = num
    },
    isHlsFlv(url) {
      const extension = url.substring(url.lastIndexOf('.') + 1)
      if (extension.toLowerCase() === 'm3u8') {
        return 'hls'
      }
      if (extension.toLowerCase() === 'flv') {
        return 'flv'
      }
      return ''
    },
    // play(url, video) {
    //   if (this.isHlsFlv(url) === 'hls') {
    //     var myPlayer = new Hls()
    //     console.log(myPlayer)
    //     myPlayer.loadSource(url)
    //     myPlayer.attachMedia(video)
    //     myPlayer.on(Hls.Events.MANIFEST_PARSED, function() {
    //       video.play()
    //     }
    //     )
    //   } else if (this.isHlsFlv(url) === 'flv') {
    // 暂不使用这种格式播放
    // const myPlayer = flvjs.createPlayer({
    //   type: 'flv',
    //   url: url
    // })
    // myPlayer.attachMediaElement(video)
    // myPlayer.load()
    // myPlayer.play()
    //   } else {
    //     console.log('错误类型地址')
    //   }
    // },
    // 录像回放
    setPlayback(val, snum = 0) {
      this.videoPlayer.playback({
        snum,
        records: val.records || [],
        path: val.url || val.path,
        startTime: val.startTime,
        endTime: val.endTime,
        redirect: val.redirect,
        playStartTime: val.playStartTime || val.startTime,
        playEndTime: val.playEndTime || val.endTime
      })
    },
    initWidth() {
      this.screenWidth = document.body.clientWidth
      if (this.screenWidth < 991) {
        return '90%'
      } else if (this.screenWidth < 1400) {
        return '60%'
      } else {
        return '55%'
      }
    },
    close() {
      this.$emit('close')
      this.initVideo(1)
    }
  }
}
</script>

<style lang="less" scoped>
    .videlSytle {
        background:url('~@/assets/noVideo.png') no-repeat center;background-size:45% 45%;
    }
</style>
